<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\Material as MaterialService;
use app\common\service\Sku as SkuService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderException as OrderExceptionService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderMergeCut as OrderMergeCutService;
use app\common\service\StallFeed as StallFeedService;
use think\Db;
/**
 * 成本管理
 * @author sparkguo
 */
class CostingV2 extends Admin
{

	protected $hisiModel = '';//模型名称[通用添加、修改专用]
	protected $hisiValidate = '';
	protected $hisiAddScene = '';//添加数据验证场景名
	protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }


	/**
	 * 物料成本核算
	 * @return \think\response\Json|string
	 */
	public function costList()
	{
		$factoryKV = getFactoryKV(true);
		$systemUserKV = getSystemUserKV(null);
		$orderSizeService = new OrderSizeService();
		$materialService = new MaterialService();
        $stallsKV = getStallsKV();
		$materialStockCuttingService = new MaterialStockCuttingService();
		$orderMaterialItemService = new OrderMaterialItemService();
		if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
			$where      = $data = [];
            $stat = $this->request->param('a/s','');
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$costAuditStatus    = $this->request->param('cost_audit_status/s');
			$orderStatus    = $this->request->param('order_status/s');
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$costAuditDateRange    = $this->request->param('cost_audit_date_range/s');
			$sku    = $this->request->param('sku/s');
			$isAutoImport    = $this->request->param('is_auto_import/s');
			$createDateRange    = $this->request->param('create_date_range/s');
            $urgeOrder    	= $this->request->param('urge_order/d', 2);
			$caichuangOverTime    = $this->request->param('caichuang_over_time/s');
			$factorId      = $this->request->param('factory_id/d', 0);
			$exceptionNum      = $this->request->param('exception_num/d', -1);
			$isShare  = $this->request->param('is_share/d', 2);
			$isOmc  = $this->request->param('is_omc/d', 2);
			$export     = $this->request->param('export/d', 0);
			$cut_user=$this->request->param('caichuang_user_name/s');
			set_time_limit(0);
			ini_set('memory_limit', '1024M');

			if ($export) {
				$page = 1;
				$limit = 99999;
			}
			if ($isShare!=2) {
				$subQuerys = db('order_material')->where('is_share',$isShare)->distinct(true)->field('order_id')->buildSql();
				$where[] = ['id', 'exp', Db::raw("in({$subQuerys})")];
    		}
			if ($isOmc!=2) {
				$subQueryo = db('order_merge_cut')->distinct(true)->field('client_ordernum')->select();
				$clientOrdernums=[];
				foreach ($subQueryo as $komc => $vomc) {
					$orderNumStr= arrayGet($vomc, "client_ordernum",'');
					$orderNumArr= explode(',', $orderNumStr);
					$clientOrdernums= array_merge($clientOrdernums,$orderNumArr);
				}
				$where[] = ['client_ordernum', 'in', $clientOrdernums];
    		}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }
            //订单加一级
            order_level($where,'');
            if ($urgeOrder != 2) {
                switch ($urgeOrder){
                    case 0:
                        $subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("om.caigou_cost_status=0 and om.is_make_tag=1 and m.type !='accessories'")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['id', 'exp', Db::raw("not in({$subQuery})")];
                        break;
                    case 1:
                        $subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("om.caigou_cost_status=0 and om.is_make_tag=1 and m.type !='accessories'")->distinct(true)->field('om.order_id')->buildSql();
                        $where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
                        break;
                }
            }
			$where[] = ['stock_type', '<', 10];
			if ($exceptionNum>-1 && $exceptionNum > 0) {
				$where[] = ['exception_num', '>', 0];
			}
			if ($exceptionNum>-1&&$exceptionNum == 0) {
				$where[] = ['exception_num', '=', 0];
			}
			if ($costAuditStatus > -1) {
				$where[] = ['cost_audit_status', '=', $costAuditStatus];
			}
			if ($factorId) {
    			$where[] = ['factory_id', '=', $factorId];
    		}
			if ($isAutoImport > 0) {
				$where[] = ['is_auto_import', '=', $isAutoImport];
			}

			if ($orderStatus == 99) $where[] = ['status', '=', 99];
			elseif ($orderStatus == 999) $where[] = ['client_status', '=', 99];
			elseif ($orderStatus != '') {
				switch ($orderStatus){
					case 1:
						$where[] = ['caigou_status', '=', 1];
						$where[] = ['caichuang_status', '=', 0];
						break;
					case 2:
						$where[] = ['caichuang_status', '=', 1];
						$where[] = ['chejian_status', '=', 0];
						break;
					case 3:
						$where[] = ['chejian_status', '=', 1];
						$where[] = ['tail_status', '=', 0];
						break;
					case 4:
						$where[] = ['tail_status', '=', 1];
						$where[] = ['status', '=', 0];
						break;
					case 5:
						$where[] = ['tail_status', '=', 1];
						$where[] = ['real_shipment_status', '=', 0];
						break;
					case 6:
						$where[] = ['real_shipment_status', '=', 1];
						$where[] = ['status', '=', 1];
						break;
					case 7:
						$where[] = ['status', '=', 2];
						break;
				}
			}

			if ($clientOrdernum != '') {
				$where[] = ['client_ordernum', 'in', $clientOrdernum];
			}
			if ($sku != '') {
				$where[] = ['sku', 'like', "%".$sku."%"];
			}
            if ($cut_user != '') {
                $where[] =  ['caichuang_user_id', 'in',  db('system_user')->where('nick', 'like', "%{$cut_user}%")->column('id')];
            }
			if ($costAuditDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $costAuditDateRange));
				$where[] = ['cost_audit_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($caichuangOverTime != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverTime));
				$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
			}
			$order = "FIELD(status,1,0,2,99), caigou_cost_status DESC, id DESC";//cost_audit_status ASC,
			$data['data'] = db('order')->where($where)->page($page)->limit($limit)->orderRaw($order)->select();
			$skuService = new SkuService();
			$orderMaterialService = new OrderMaterialService();
			$orderMergeCutService = new OrderMergeCutService();
			$orderExceptionService= new OrderExceptionService();
			foreach ($data['data'] as $k => $v) {
				$data['data'][$k]['exception']=0;
				$oeList=$orderExceptionService->getListByOrderId($v['id'], 'id');
				if($oeList) $data['data'][$k]['exception']=1;
				$osList = $orderSizeService->getListByOrderId($v['id']);
				$data['data'][$k]['osList'] = $osList;
				$data['data'][$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
				$data['data'][$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
				$data['data'][$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
				$data['data'][$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
				$data['data'][$k]['omList'] = $orderMaterialService->getListByOrderId($v['id']);
				$data['data'][$k]['om_status']=0;
				$omcInfo=$orderMergeCutService->getInfoByClientOrdernum($v['client_ordernum'], 'id,client_ordernum');
				if($omcInfo) {
				    $data['data'][$k]['omc_status']=1;
				    $data['data'][$k]['omc_client_ordernums']=$omcInfo['client_ordernum'];
                }
				if ($export) {
					if(!$data['data'][$k]['omList']) unset($v);
				}
				foreach ($data['data'][$k]['omList'] as $kom => $vom) {
                    $data['data'][$k]['omList'][$kom]['caichuang_shiji_dosage']=$vom['caichuang_shiji_dosage']=$vom['caichuang_shiji_dosage'];
					$materialId = $vom['material_id'];
                    $trueWeightn=0;
                    $trueWeight=db('checkcloth_shrink')->where("order_id=".$vom['order_id']." and material_id=".$vom['material_id'])->column("true_weight");
                    if($trueWeight) $data['data'][$k]['omList'][$kom]['true_weight']=$trueWeightn= array_sum($trueWeight)/count($trueWeight);
                    $tubeWeightret=db('checkcloth_shrink')->where("order_id=".$vom['order_id']." and material_id=".$vom['material_id'])->orderRaw("id DESC")->field("weight_page")->find();
                    $data['data'][$k]['omList'][$kom]['rel_tube_weight']=empty($tubeWeightret['weight_page']) ? 0.00 : $tubeWeightret['weight_page'] ;
    				$data['data'][$k]['omList'][$kom]['omiList'] = $orderMaterialItemService->getListByOrderMaterialId($vom['mid']);
    				$data['data'][$k]['omList'][$kom]['mscInfo'] =$mscInfo= $materialStockCuttingService->getInfoByMaterialId($v['id'], $materialId);
    				foreach ($data['data'][$k]['omList'][$kom]['omiList'] as $vomi){
						if ($vomi['caichuang_remark'] != ''){
							$data['data'][$k]['omList'][$kom]['caichuang_remark'].=$vomi['cloth_num_full'].":".$vomi['caichuang_remark']."<br>";
						}
						if (!empty($mscInfo) && $mscInfo['caichuang_remark']!=''){
							$data['data'][$k]['omList'][$kom]['caichuang_remark'].="库存面料：".$mscInfo['caichuang_remark'];
						}
					}
					unset($mscInfo);

					$wkereom=[
						['material_id','=',$vom['material_id']],
						['order_id','=',$vom['order_id']]
					];
                    $data['data'][$k]['omList'][$kom]['quantity']=$v['quantity'];
					$data['data'][$k]['omList'][$kom]['shiji_weight']=$shijiWeight=round($vom['weight_shrink']-$vom['weight_page'],2);
					$data['data'][$k]['omList'][$kom]['shicai_count']=$vom['shicai_count']=$shicaiCount=array_sum(array_column($osList, 'shicai_count'));
					$data['data'][$k]['omList'][$kom]['metre']=0;
					$matre = db('material_stock')->field('metre')->where($wkereom)->find();
					if ($matre) $data['data'][$k]['omList'][$kom]['metre']=$matre['metre'];
					$data['data'][$k]['omList'][$kom]['return_num']=db('material_return')->field('id')->where('order_material_id',$vom['mid'])->count();
					$omInfo=$data['data'][$k]['omList'][$kom];
					$heightTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_wheat_height'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_wheat_height', 0);
					$lowTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_wheat_low'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_wheat_height', 0);
					$neadendTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_neadend'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_neadend', 0);
					$stripTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_strip'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_strip', 0);
					$allStripDosage=$omInfo['caichuang_strip_dosage']*$shicaiCount;
                    $data['data'][$k]['omList'][$kom]['source_custom_simple_cost']=$vom['custom_simple_cost'];
                    $data['data'][$k]['omList'][$kom]['source_custom_simple_cost_2']=$data['data'][$k]['omList'][$kom]['custom_simple_cost_2']=$vom['custom_simple_cost_2']=sprintf("%.2f" ,$vom['customer_dosage']*$vom['customer_price']*(1+$vom['loss']/100));
					$data['data'][$k]['omList'][$kom]['labu_lenght']=$labuLenght=round(($heightTotal*$omInfo['caichuang_wheat_height_length']) + ($lowTotal*$omInfo['caichuang_wheat_low_length']) + $neadendTotal + $stripTotal + $allStripDosage + ($heightTotal+$lowTotal)*0.06, 2);//拉布米长
					$scLenght=$vom['checkcloth_length']==0?$vom['shrink_length']:$vom['checkcloth_length'];
					$data['data'][$k]['omList'][$kom]['metre_dif']=$metreDif=round($scLenght-$vom['billing_caigou_count'],2);//米数差异
					$data['data'][$k]['omList'][$kom]['metre_dif_count']=round($metreDif*$vom['caigou_unitprice'],2); //米数差异金额
					$data['data'][$k]['omList'][$kom]['metre_dif_pre']=$metrePre=($vom['billing_caigou_count']==0?0:round(($vom['checkcloth_length']/$vom['billing_caigou_count']-1)*100,2))."%"; //米数差异率
					$data['data'][$k]['omList'][$kom]['billing_caigou_kgcount_dif']=$billingCaigouKgcountDif=round($shijiWeight-$vom['billing_caigou_kgcount'],2);//公斤差异
                    $disscount_pic=$vom['fabric_price_amount']+$vom['dosage_price_amount'];
                    $data['data'][$k]['omList'][$kom]['col1']=round(($vom['custom_simple_cost'] +$disscount_pic)*$vom['shicai_count'] ,2); //客户物料单项金额
                    $data['data'][$k]['omList'][$kom]['col1_2']=$vom['col1_2']=round(($vom['custom_simple_cost_2']+$disscount_pic)*$vom['shicai_count'],2); //客户物料单项金额

                    $win_money=sprintf("%.2f",round($vom['col1_2']-$vom['caigou_subtotal_money'],2));
                    $data['data'][$k]['omList'][$kom]['win_money']=$win_money;//赢亏情况
                    $data['data'][$k]['omList'][$kom]['win_pre']= $vom['col1_2'] > 0? round($win_money/$vom['col1_2'] * 100,2) .'%' : "0.00%";//赢亏占比
					$data['data'][$k]['omList'][$kom]['billing_caigou_kgcount_dif_count']=round($billingCaigouKgcountDif*$vom['billing_caigou_kgprice'],2); //公斤差异金额
					$data['data'][$k]['omList'][$kom]['caigou_unitprice_dif']=$caigouUnitpriceDif=round($vom['customer_price']-$vom['caigou_unitprice'],2);//采购差异
					$data['data'][$k]['omList'][$kom]['caigou_unitprice_dif_count']=round($caigouUnitpriceDif*($vom['customer_dosage'] * (1+$vom['loss']/100))*$shicaiCount,2); //采购差异金额
                    $data['data'][$k]['omList'][$kom]['weight_dif']=$weightDif=round(floatval($vom['mInfo']['weight'])-$trueWeightn,2);//克重差异
                    $data['data'][$k]['omList'][$kom]['width_dif']=$widthDif=round(floatval($vom['true_fabric_width'])-floatval($vom['mInfo']['fabric_width']),2);//幅宽差异
					$data['data'][$k]['omList'][$kom]['width_dif']=$widthDif=round(floatval($vom['true_fabric_width'])-floatval($vom['mInfo']['fabric_width']),2);//幅宽差异
					$data['data'][$k]['omList'][$kom]['bsp_dif']=$bspDif=round(($vom['customer_dosage']-$vom['caichuang_shiji_dosage']),2);//唛架差异
					$data['data'][$k]['omList'][$kom]['bsp_dif_count']=round($bspDif*$vom['caigou_unitprice']*$shicaiCount,2); //唛架差异金额
					$csLenght=$vom['shrink_length']==0?$vom['checkcloth_length']:$vom['shrink_length'];
					$data['data'][$k]['omList'][$kom]['labu_lenght_dif']=$labuLenghtDif=round($labuLenght-$csLenght,2);//拉布米数差异
					$data['data'][$k]['omList'][$kom]['labu_lenght_dif_count']=round($labuLenghtDif*floatval($vom['caigou_unitprice']),2); //拉布差异金额
					$data['data'][$k]['omList'][$kom]['preCaiCount']=$perCaiCount=$vom['customer_dosage']==0?0:round($vom['billing_caigou_count']/($vom['customer_dosage'] * (1+$vom['loss']/100)),2);//预裁数
					$data['data'][$k]['omList'][$kom]['caichuang_dif']=$caichuangDif=round($shicaiCount-$vom['yingcai_count'],0);//裁剪差异数
					$data['data'][$k]['omList'][$kom]['caichuang_dif_count']=round($caichuangDif*$vom['custom_simple_cost'],2); //裁剪差异金额
                    //客户幅宽/克重/米--第1次与第n次处理
                    $data['data'][$k]['omList'][$kom]['fabric_width_once'] = $vom['fabric_width_once'] = intval($vom['fabric_width_once'] <= 0 ? $vom['fabric_width'] : $vom['fabric_width_once']);
                    $data['data'][$k]['omList'][$kom]['weight_once'] = $vom['weight_once'] = intval($vom['weight_once'] <= 0 ? $vom['weight'] : $vom['weight_once']);
                    $data['data'][$k]['omList'][$kom]['metre_once'] = round(($vom['fabric_width_once'] == 0 || $vom['weight_once'] == 0) ? 0 : 10000 / $vom['fabric_width_once'] / $vom['weight_once'], 2);
                    $data['data'][$k]['omList'][$kom]['mInfo']['fabric_width'] = $minfo_fabric_width = intval($vom['mInfo']['fabric_width']);
                    $data['data'][$k]['omList'][$kom]['mInfo']['weight'] = $minfo_weight = intval($vom['mInfo']['weight']);
                    $data['data'][$k]['omList'][$kom]['mInfo']['metre'] = round(($minfo_fabric_width == 0 || $minfo_weight == 0) ? 0 : 10000 / $minfo_fabric_width / $minfo_weight, 2);
                }
				if($data['data'][$k]['omList']){
					$osList=$orderSizeService->getListByOrderId($v['id'], 'shicai_count');
					$data['data'][$k]['shicai_count']=array_sum(array_column($osList, 'shicai_count'));
				}

				unset($oeList, $osList);
			}

			// 导出
			if ($export) {
				$this->_exportXls('物料成本核算-' .date('YmdHis'), $data['data']);
				exit;
			}
            $data['factoryStat']=[];
            if($stat=="factory"){
                $data['factoryStat']=$this->orderCostTotals($where);
            }

			$data['count'] = db('order')->where($where)->count('id');
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'factoryKV' => [0 => '请选择'] + $factoryKV,
            'stallsKV' => $stallsKV,
			'orderFrom' => [0 => '请选择'] + config('mimo.order_from'),
			'clientStatus' => config('mimo.client_status'),
		];
		return $this->assign($assign)->fetch();
	}

    public function orderCostTotals($where=[]){
        $factoryKV = getFactoryKV(false);
        $tbPre = config('database.prefix');
        $factoryOrderCount=db( 'order')->where($where)->group('factory_id')->column('count(id) as count,factory_id','factory_id');
        $listA = db('order_size')->where('order_id', 'IN', function ($query) use($tbPre, $where) {
            $query->table($tbPre . 'order')->where($where)->field('id');
        })->group('factory_id')->column('sum(order_count) as order_count,sum(shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(daohuo_count) as daohuo_count','factory_id');

        $listB = db('order_material order_m')->where('order_id', 'IN', function ($query) use($tbPre, $where) {
            $query->table($tbPre . 'order')->where($where)->field('id');
        })->group('factory_id')->where('material.type','in',['fabric','lining'])
            ->join('material material', 'order_m.material_id = material.id','left')
            ->column('sum(caigou_subtotal_money) as cost_money_total,sum(fabric_price_amount) as fabric_price_amount,sum(dosage_price_amount) as dosage_price_amount,
        sum((custom_simple_cost+fabric_price_amount+dosage_price_amount)*shicai_count) as customer_cost_amont,
        count(id) as material_count,
        sum(case when (custom_simple_cost+fabric_price_amount+dosage_price_amount)*shicai_count-caigou_subtotal_money > 0 then 1 else 0 end) as win_order_num,
        sum(case when (custom_simple_cost+fabric_price_amount+dosage_price_amount)*shicai_count-caigou_subtotal_money < 0 then 1 else 0 end) as lose_order_num,
        sum(case when (custom_simple_cost+fabric_price_amount+dosage_price_amount)*shicai_count-caigou_subtotal_money < 0 then (custom_simple_cost+fabric_price_amount+dosage_price_amount)*shicai_count-caigou_subtotal_money else 0 end) as lose_money_total,
        sum((custom_simple_cost+fabric_price_amount+dosage_price_amount)*shicai_count-caigou_subtotal_money) as profit_loss','factory_id');
        $listC = db('material_stock')->where('order_id', 'IN', function ($query) use($tbPre, $where) {
            $query->table($tbPre . 'order')->where($where)->field('id');
        })->group('factory_id')->column('sum(metre_left) as metre_left,sum(unit_price_metre*metre_left) as metre_money','factory_id');

        $result = [];
        foreach ($listA as $factoryId => $v) {
            $customer_cost_amount=sprintf('%.2f',arrayGet(arrayGet($listB, $factoryId, []), 'customer_cost_amont', 0));
            $win_order_num=arrayGet(arrayGet($listB, $factoryId, []), 'win_order_num', 0);
            $lose_order_num=arrayGet(arrayGet($listB, $factoryId, []), 'lose_order_num', 0);
            $material_count=arrayGet(arrayGet($listB, $factoryId, []), 'material_count', 0); //总物料单数
            $win_order_per=$lose_order_num > 0? sprintf('%.2f',$win_order_num/$material_count) * 100 .'%' : "0.00%";
            $lose_order_per=$lose_order_num > 0? sprintf('%.2f',$lose_order_num/$material_count) * 100 .'%' : "0.00%";
            $result[] = [
                'default_val'=>'--',
                'order_count'=>arrayGet($v, 'order_count', 0),
                'order_total'=>isset($factoryOrderCount[$factoryId]) ? $factoryOrderCount[$factoryId] : 0 ,
                'shicai_count'=>arrayGet($v, 'shicai_count', 0),
                'jiaohuo_count'=>arrayGet($v, 'jiaohuo_count', 0),
                'daohuo_count'=>arrayGet($v, 'daohuo_count', 0),
                'cost_money_total'=>sprintf('%.2f',round(arrayGet(arrayGet($listB, $factoryId, []), 'cost_money_total', 0),3)),
                'customer_cost_amount'=>$customer_cost_amount,
                'win_order_num'=>$win_order_num,
                'win_order_per'=>$win_order_per,
                'lose_order_num'=>arrayGet(arrayGet($listB, $factoryId, []), 'lose_order_num', 0),
                'material_count'=>$material_count,
                'lose_order_per'=>$lose_order_per,
                'lose_money_total'=>sprintf('%.2f',arrayGet(arrayGet($listB, $factoryId, []), 'lose_money_total', 0)),
                'win_per'=>$customer_cost_amount > 0? round(arrayGet(arrayGet($listB, $factoryId, []), 'profit_loss', 0)/$customer_cost_amount * 100,2) .'%' : "0.00%",
                'profit_loss'=>round(arrayGet(arrayGet($listB, $factoryId, []), 'profit_loss', 0),3),
                'metre'=>sprintf('%.2f',arrayGet(arrayGet($listC, $factoryId, []), 'fabric_price_amount', 0)),
                'metre_money'=>round(arrayGet(arrayGet($listC, $factoryId, []), 'metre_left', 0)),
                'fabric_price_amount'=>round(arrayGet(arrayGet($listB, $factoryId, []), 'metre_money', 0)),
                'dosage_price_amount'=>round(arrayGet(arrayGet($listB, $factoryId, []), 'dosage_price_amount', 0)),
                'factory_id'=>$factoryId,
                'factory'=>arrayGet($factoryKV, $factoryId,'未分组'),
            ];
        }
        return $result;
    }

    /**
     * 成本核算保存采购成本备注 唛架备注
     * @author sparkguo 361911768
     */
    public function orderCostRemark() {
        $orderId       = $this->request->param('order_id/d', 0);
        $costRemark   = $this->request->param('cost_remark/s', '');
        $caichuangRemark=$this->request->param('caichuang_remark/s', '');
        $upData = [
            'caigou_cost_remark' => $costRemark,'caichuang_remark'=>$caichuangRemark,
            'update_time' => time(),
        ];
        if(empty($costRemark)){ unset($upData['caigou_cost_remark']); }
        if(empty($caichuangRemark)){ unset($upData['caichuang_remark']); }
        $ret = db('order')->where('id', $orderId)->update($upData);
        $this->addOrderLog($orderId, '', "保存备注".json_encode($upData));
        if ($ret) {
            return $this->Json(1, '备注保存成功');
        } else return $this->Json(0);
    }

    /**
     * 保存采购核价备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function caigouPricing() {
        $orderId       = $this->request->param('order_id/d', 0);
        $remark   = $this->request->param('remark/s', '');
        $upData = [
            'caigou_pricing' => $remark,
            'update_time' => time(),
        ];
        $ret = db('order')->where('id', $orderId)->update($upData);
        $this->addOrderLog($orderId, '', "保存采购核价备注[{$remark}]");
        if ($ret) {
            return $this->Json(1, '保存采购核价备注成功');
        } else return $this->Json(0);
    }

    /**
     *
     *补退明细
     * @date 2021年3月13日
     *
     */
    public function stallFeedDetail(){
        $mid  = $this->request->param('mid/d', 0);
        $stallsKV = getStallsKV();
        $orderMaterialService = new OrderMaterialService();
        $omInfo=$orderMaterialService->getInfoById($mid, "client_ordernum,material_id,fabric_width,weight,customer_price");
        if(!$omInfo) return $this->error("数据异常");
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {

            $materialService = new MaterialService();
            $orderMaterialItemService = new OrderMaterialItemService();
            $clientOrdernum  = $this->request->param('client_ordernum/s');

            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $where      = $data = [];

            $where[] = ['order_material_id', '=', $mid];

            $where[] = ['original', '=', 0];

            $order="id desc";
            $data['data'] = db('stall_feed')->where($where)->page($page)->limit($limit)->order($order)->select();

            $data['mInfo']=$materialService->getInfoById($omInfo['material_id'],'supplier');
            $data['mInfo']['weight'] = $omInfo['weight'];
            $data['mInfo']['fabric_width'] = $omInfo['fabric_width'];
            $sellerNameKeyDatas=array_flip($stallsKV);
            $sellerOtherNames=[];
            $seller=db('stalls')->where([['othernames','<>','']])->order("id asc")->column('othernames', 'id');
            foreach ($seller as $id=>$othername){
                $othernameArr=explode('，',trim($othername,'，'));
                foreach ($othernameArr as $othernameStr){
                    $sellerOtherNames[$othernameStr]=$id;
                }
            }
            foreach ($data['data'] as $key => &$value) {
                $data['data'][$key]['caigou_amount']=sprintf("%.2f",$value['billing_caigou_count_feed']*$value['caigou_unitprice']);
                $data['data'][$key]['customer_price']=$omInfo['customer_price'];
                $value['caigou_unitprice']=substr($value['caigou_unitprice'],-1)=='0' ? substr($value['caigou_unitprice'],0,strlen($value['caigou_unitprice'])-1) :$value['caigou_unitprice'];
                $data['data'][$key]['stall_id']=$data['data'][$key]['stall_id']==0 ? (isset($sellerNameKeyDatas[$data['mInfo']['supplier']]) ? $sellerNameKeyDatas[$data['mInfo']['supplier']] : 0 ) : $data['data'][$key]['stall_id'];//匹配档口名称
                //供应商为空则尝试匹配其它关联档口名称
                $data['data'][$key]['stall_id']=$data['data'][$key]['stall_id']==0 ? (isset($sellerOtherNames[$data['mInfo']['supplier']]) ? $sellerOtherNames[$data['mInfo']['supplier']] : 0 ) : $data['data'][$key]['stall_id'];
                $data['data'][$key]['mInfo'] = $data['mInfo'];
            }
            $data['count'] = db('stall_feed')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [
            'client_ordernum'=>$omInfo['client_ordernum'],
            'mid' => $mid,
            'stallsKV' => ['0' => '请选择'] + $stallsKV,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 采购成本补料
     * @author KING
     * @date 2020年7月31日
     *
     */
    public function costFeed() {
        $mid  = $this->request->param('mid/d', 0);
        $number = $this->request->post('number/f', 0); // 补料
        $billingCaigouKgcount=$this->request->post('billing_caigou_kgcount/f', 0); // 开单公斤数
        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService=new OrderMaterialItemService();
        $stallFeedService=new StallFeedService();
        try {
            db()->startTrans();

            $omInfo = $orderMaterialService->getInfoById($mid);
            if (empty($omInfo)){
                throw new \Exception('数据异常');
            }

            $orderId = $omInfo['order_id'];

            $billingCaigouCount = $omInfo['billing_caigou_count'] + $number;
            //新增补退明细表记录
            $omiList=$orderMaterialItemService->getListByOrderMaterialId($mid,"stalls_id");
            if($omiList) $sfData['stall_id']=$omiList[0]['stalls_id'];
            $sfData=[
                'billing_caigou_count_feed'=>$number >= 0 ? '+'.abs($number) : $number,
                'billing_caigou_kgcount' => $billingCaigouKgcount,
                'order_material_id'=>$mid,
                'order_id'=>$omInfo['order_id'],
                'client_ordernum'=>$omInfo['client_ordernum'],
                'material_id'=>$omInfo['material_id'],
                'admin_id'=>ADMIN_ID,
                'update_time' => time(),
                'create_time' => time(),
            ];
            db('stall_feed')->insert($sfData);
            //同时更新order_material和order
            $sfList=$stallFeedService->getListByMid($omInfo['mid']);
            $caigouSubtotalMoney = $omInfo['caigou_unitprice'] * $omInfo['billing_caigou_count_ori'];
            foreach ($sfList as $key => $value) {
                $caigouSubtotalMoney = $caigouSubtotalMoney+($value['caigou_unitprice']*$value['billing_caigou_count_feed']);
            }
            $oud = array(
                'update_time' => time(),
                'billing_caigou_count_feed' =>  $number >= 0 ? '+'.abs($number) : $number,
                'billing_caigou_count' => $billingCaigouCount,
               // 'caigou_subtotal_money' => round($caigouSubtotalMoney, 2),
            );
            $res = db('order_material')->where('mid', $mid)->update($oud);
            $orderInfo = $orderService->getInfoById($orderId);
            if ($orderInfo['status'] == 0) $orderData['status'] = 1;
            $orderData['update_time'] = time();

            // 采购合计金额stallFeedDetail
            $orderData['caigou_total_money'] = $orderMaterialService->getAllCaigouSubtotalMoney($orderId);
            db('order')->where('id', $orderId)->update($orderData, "id = " . $orderId);
            $this->addOrderLog($orderId, $orderInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]补料".$number);

            db()->commit();
            $res = [
                'order_id' => $orderId,
                'billing_caigou_count' => $billingCaigouCount,
                'caigou_subtotal_money' => $caigouSubtotalMoney,
                'caigou_total_money' => $orderData['caigou_total_money']
            ];
            return $this->Json(1, '', $res);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    //采购入单确认功能
    public function stallFeedConfirm() {
        $id  = $this->request->param('id/d', 0);
        $stallFeedType   = $this->request->param('stall_feed_type/s','');
        $stallId   = $this->request->param('stall_id/d', 0);
        $caigouUnitprice   = $this->request->param('caigou_unitprice/f', 0);
        $billingCaigouKgprice   = $this->request->param('billing_caigou_kgprice/f', 0);
        $billingCaigouKgcount   = $this->request->param('billing_caigou_kgcount/f', 0);
        $roll_num=$this->request->param('roll_num/d', 0);
        $stallOrderTime   = $this->request->param('stall_order_time/s', '');
        $stallOrder   = $this->request->param('stall_order/s', '');
        $billingCaigouCountFeed   = $this->request->param('billing_caigou_count_feed/s', '');
        $action_event=$this->request->param('action_event/s', '');
        if($action_event=='delete'){
            $orderMaterialService = new OrderMaterialService();
            $stallFeedService= new StallFeedService();
            // 记录原始开单采购数
            $sfInfo = $stallFeedService->getInfoById($id);
            if (empty($sfInfo)){
                throw new \Exception('数据异常');
            }
            db()->startTrans();
            //删除入单信息
            db('stall_feed')->where('id', $id)->delete();
            $omInfo=$orderMaterialService->getInfoById($sfInfo['order_material_id'], "customer_price,billing_caigou_count,caigou_unitprice,mid,caigou_subtotal_money,billing_caigou_count_ori");
            $lastPurcharePrice=db('stall_feed')->where([['order_material_id', '=', $omInfo['mid']],['caigou_unitprice','>',0]])->field("caigou_unitprice,billing_caigou_kgprice")->order('id desc')->find();
            $sfList = $stallFeedService->getListByMid($omInfo['mid']);
            $roll_num_amount=$billing_caigou_kgcount=$billingCaigouCount=0;
            $billingCaigouCountFeedStr = '';
            $billingCaigouCount=$omInfo['billing_caigou_count_ori'];
            $caigouSubtotalMoney = $omInfo['caigou_unitprice'] * $omInfo['billing_caigou_count_ori'];

            foreach ($sfList as $key => $value) {
                if ($value['original'] == 1) continue; // 初单的金额无需再次计入
                $billingCaigouCountFeed = floatval($value['billing_caigou_count_feed']);
                $billingCaigouCount+=$value['billing_caigou_count_feed'];
                $roll_num_amount+=$value['billing_roll_num'];
                $caigouSubtotalMoney = ($value['caigou_unitprice']*$billingCaigouCountFeed) + $caigouSubtotalMoney;
                $billing_caigou_kgcount+=$value['billing_caigou_kgcount'];
                $billingCaigouCountFeedStr = $billingCaigouCountFeed < 0 ? $billingCaigouCountFeed : '+'.abs($billingCaigouCountFeed);
            }
            $oudata = array(
                'update_time' => time(),
                'billing_caigou_count' => $billingCaigouCount, //开单采购总数(米)
                'caigou_subtotal_money' => round($caigouSubtotalMoney, 2), //采购物料总金额
                'billing_caigou_kgcount'=>$billing_caigou_kgcount,
                'billing_caigou_count_feed' => $billingCaigouCountFeedStr,
                'billing_roll_num'=>$roll_num_amount,
            );
            if(!empty($lastPurcharePrice)){
                $oudata['caigou_unitprice']=$lastPurcharePrice['caigou_unitprice'];
            }
            db('order_material')->where('mid',$sfInfo['order_material_id'])->update($oudata);
            $this->addOrderLog($sfInfo['order_id'], $sfInfo['client_ordernum'], "物料[".getMaterialName($sfInfo['material_id'])."]入单操作 删除一个入单信息");
            db()->commit();
            $result = [
                'order_id' =>  $sfInfo['order_id'],
                'billing_caigou_count' => $billingCaigouCount,
                'billing_caigou_kgcount'=>$billing_caigou_kgcount,
                'caigou_subtotal_money' => $oudata['caigou_subtotal_money'], //采购物料单项总金额
                'caigou_unitprice'=>$lastPurcharePrice['caigou_unitprice'],
                'billing_caigou_kgprice'=>$lastPurcharePrice['billing_caigou_kgprice']
            ];
            return $this->Json(1,'',$result);die;
        }
        if($stallId==0) return $this->error('请选择供应商');
        try {
            db()->startTrans();
            $orderMaterialService = new OrderMaterialService();
            $stallFeedService= new StallFeedService();
            // 记录原始开单采购数
            $sfInfo = $stallFeedService->getInfoById($id);
            if (empty($sfInfo)){
                throw new \Exception('数据异常');
            }
            if ($billingCaigouCountFeed == '' || floatval($billingCaigouCountFeed) == 0) {
                throw new \Exception(',采购入单填写错误,米数数据不能为零');
            }
            $orderId = $sfInfo['order_id'];
            $billingCaigouCountFeed = floatval($billingCaigouCountFeed);
            $omInfo=$orderMaterialService->getInfoById($sfInfo['order_material_id'], "customer_price,billing_caigou_count,caigou_unitprice,mid,caigou_subtotal_money,billing_caigou_count_ori");

            $oud = [
                'update_time' => time(),
                'status' => 1,
                'stall_feed_type'=>$stallFeedType,
                'billing_caigou_count_feed'=> $billingCaigouCountFeed,
                'caigou_unitprice' => $caigouUnitprice,
                'billing_caigou_kgprice' => $billingCaigouKgprice,
                'billing_caigou_kgcount'=>$billingCaigouKgcount,
                'billing_roll_num'=>$roll_num,
                'stall_id' => $stallId,
                'stall_order'=>$stallOrder,
                'stall_order_time'=>strtotime($stallOrderTime)?strtotime($stallOrderTime):0,
                'settle_unitprice'=> min([$caigouUnitprice, $omInfo['customer_price']]),
            ];
            $oud['settle_amount'] = round($oud['caigou_unitprice'] * abs(floatval($billingCaigouCountFeed)), 2);
            $res = db('stall_feed')->where('id', $id)->update($oud);
            $lastPurcharePrice=db('stall_feed')->where([['order_material_id', '=', $omInfo['mid']],['caigou_unitprice','>',0]])->field("caigou_unitprice,billing_caigou_kgprice")->order('id desc')->find();

            //同时更新order_material表
            $billingCaigouCount=$omInfo['billing_caigou_count']-$sfInfo['billing_caigou_count_feed']+$billingCaigouCountFeed;
            $caigouSubtotalMoney = $omInfo['caigou_unitprice'] * $omInfo['billing_caigou_count_ori'];
            $sfList = $stallFeedService->getListByMid($omInfo['mid']);
            $roll_num_amount=$billing_caigou_kgcount=$billingCaigouCount=0;
            $billingCaigouCountFeedStr = '';
            $billingCaigouCount=$omInfo['billing_caigou_count_ori'];
            foreach ($sfList as $key => $value) {
                if ($value['original'] == 1) continue; // 初单的金额无需再次计入
                $billingCaigouCountFeed = floatval($value['billing_caigou_count_feed']);
                $billingCaigouCount+=$value['billing_caigou_count_feed'];
                $roll_num_amount+=$value['billing_roll_num'];
                $caigouSubtotalMoney = ($value['caigou_unitprice']*$billingCaigouCountFeed) + $caigouSubtotalMoney;
                //$caigouSubtotalMoney +=$value['billing_caigou_count_feed']<0 ? -$value['settle_amount'] : $value['settle_amount'];
                $billing_caigou_kgcount+=$value['billing_caigou_kgcount'];
                $billingCaigouCountFeedStr = $billingCaigouCountFeed < 0 ? $billingCaigouCountFeed : '+'.abs($billingCaigouCountFeed);
            }

            $oudata = array(
                'update_time' => time(),
                'billing_caigou_count' => $billingCaigouCount, //开单采购总数(米)
                'caigou_subtotal_money' => round($caigouSubtotalMoney, 2), //采购物料总金额
                'billing_caigou_kgcount'=>$billing_caigou_kgcount,
                'billing_caigou_count_feed' => $billingCaigouCountFeedStr,
                'billing_roll_num'=>$roll_num_amount,
                //'billing_caigou_kgprice'=>$lastPurcharePrice['billing_caigou_kgprice'],
            );
            if(!empty($lastPurcharePrice)){
                $oudata['caigou_unitprice']=$lastPurcharePrice['caigou_unitprice'];
            }

            db('order_material')->where('mid',$sfInfo['order_material_id'])->update($oudata);

            // 采购合计金额
            $orderData['caigou_total_money'] = $orderMaterialService->getAllCaigouSubtotalMoney($orderId);
            $orderData['update_time'] = time();
            db('order')->where('id', $orderId)->update($orderData, "id = " . $orderId);
            $this->addOrderLog($orderId, $sfInfo['client_ordernum'], "物料[".getMaterialName($sfInfo['material_id'])."]退补明细确认");

            db()->commit();
            $result = [
                'order_id' => $orderId,
                'billing_caigou_count' => $billingCaigouCount,
                'billing_caigou_kgcount'=>$billing_caigou_kgcount,
                'caigou_subtotal_money' => $oudata['caigou_subtotal_money'], //采购物料单项总金额
                'caigou_unitprice'=>$lastPurcharePrice['caigou_unitprice'],
                'billing_caigou_kgprice'=>$lastPurcharePrice['billing_caigou_kgprice']
            ];
            return $this->Json(1,'',$result);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    //检测实裁数据各表不统一的数据
    public function material(){
        $list = db('order_size order_size')
            ->field("order_id,order_size.client_ordernum,sum(order_size.shicai_count) as size_shicai_count,order_size.create_time,order_id as m_shicai_count")
            ->group('order_size.order_id')->limit(3000)->order('order_size.update_time desc')->select();//material.shicai_count as m_shicai_count,
        $altertable=Db::query("sql");
        $enddatetime=strtotime("2021-11-09");
        $startTime=strtotime('2021-10-01 00:00:00');
        $getdatasDate=[];
        while($startTime<$enddatetime){
            $getdatasDate[]=[date("Y-m-d H:i:s",$startTime),date("Y-m-d 23:59:59",$startTime)];
            $startTime+=86400;
        }
        print_r($getdatasDate);

        $assign = [
            'getdatasDate' => $getdatasDate,
        ];
        //return $this->assign($assign)->fetch();
    }

	 /**
     * 物料成本核算修改
     *
     * @date 2020年3月10日
     *
     * @throws \Exception
     */
    public function costConfirm() {
    	$mid  = $this->request->param('mid/d', 0);
    	$fabricPriceAmount   = $this->request->param('fabric_price_amount/f', 0);
    	$dosagePriceAmount   = $this->request->param('dosage_price_amount/f', 0);
		$billingCaigouCount   = $this->request->param('billing_caigou_count/f', 0);
    	$customerPrice   = $this->request->param('customer_price/f', 0);
    	$costingRemark  = $this->request->param('costing_remark', '');
        $custom_simple_cost =$this->request->param('custom_simple_cost/f', 0);
    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();

    	try {
    		db()->startTrans();

	    	// 记录原始开单采购数
	    	$omInfo = $orderMaterialService->getInfoById($mid);
	    	if (empty($omInfo)){
	    		throw new \Exception('数据异常');
	    	}

	    	$oud = [
	    		'update_time' => time(),
	    		'fabric_price_amount' => $fabricPriceAmount,
				'dosage_price_amount' => $dosagePriceAmount,
				'billing_caigou_count' => $billingCaigouCount,
                'costing_remark'=>$costingRemark,
				'customer_price' => $customerPrice,
	    	];
//            if($custom_simple_cost>0){
//                $oud['custom_simple_cost']=$custom_simple_cost;
//            }
	    	$orderId = $omInfo['order_id'];

	    	$res = db('order_material')->where('mid', $mid)->update($oud);

	    	$this->addOrderLog($orderId, $omInfo['client_ordernum'], '物料成本核算修改');

	    	db()->commit();
	    	return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }
	/**
	 * 导出xls
	 *
	 * @author KING date 2020年08月11日
	 *
	 * @param string $fileName
	 * @param array $data
	 */
	private function _exportXls($fileName, $data) {//
		$head = ['账号','下单日期','裁剪日期','裁剪员','订单数','订单类型','供应商','工厂','订单号','SKU','材料名称','开单采购数量','开单采购补量','客户幅宽/克重/米-第1次','客户幅宽/克重/米-第n次','实际幅宽/克重/米','实裁布封','开单采购公斤数',
            '开单采购公斤价','实际公斤数','采购条数','验布米长','缩水米长','拉布米长','退料匹数','退料米长','单位','客户损耗','采购物料单价','客户物料单价','实际单件用量',
            '客户单件用量','实际单件物料成本','客户单件物料成本','采购物料单项金额', '客户物料单项金额','客户物料单项金额-计算', '盈亏情况','核价','面料核价金额','用量核价金额','预裁数',
            '实裁数','余料金额','余料情况','补损金额','补损明细','米数差异','米数差异金额','米数差异率','公斤数差异','公斤差异金额','采购单价差异','采购差异金额','克重差异','幅宽差异','唛架差异','唛架差异金额',
            '拉布米数差异','拉布差异金额','裁剪差异','裁剪差异金额','料率','异常备注'];
        $export_material_type=$this->request->param('export_material_type', 'null');
		$phpExcel = getExcelObj();
		$sheet = $phpExcel->setActiveSheetIndex(0);
		$objDate = new \PHPExcel_Shared_Date();
		$objFormat = new \PHPExcel_Style_NumberFormat();
		// 表头处理
		foreach ($head as $k => $v) {
			$cellKey = getExcelLetter($k);
			$sheet->getColumnDimension($cellKey)->setWidth(20);
			$sheet->setCellValue($cellKey . "1", $v);
			$sheet->getRowDimension(1)->setRowHeight(30);
			$sheet->getStyle($cellKey . "1")->getFont()->setBold(true);
			$sheet->getStyle($cellKey . "1")->getAlignment()->setVertical('center');
			$sheet->getStyle($cellKey . "1")->getFont()->getColor()->setARGB("FF0000FF");
		}
		$skuService = new SkuService();
		$row = 2; // 当前行
		$bgArr = array(
			'type' => 'solid',
			'startcolor' => ['rgb' => 'FF0000']
		);

		foreach ($data as $k => $v) {
			if (count($v['omList']) > 1) {
				$accessoriesCount=0;$typeCount=[];
				foreach ($v['omList'] as $kt => $vt) {
					$typeAll[$k][]=$vt['mInfo']['type'];
					$typeCount=array_count_values($typeAll[$k]);
				}
				if(isset($typeCount['accessories'])){
					$accessoriesCount=$typeCount['accessories'];
				}
//				$fabricCount=0;
//				if(!isset($typeCount['fabric'])){
//					$fabricCount=1;
//				}
				$endRow = $row + count($v['omList']) - 1- $accessoriesCount;
				// '下单日期','订单号','SKU','工厂','订单类型'
				//$sheet->mergeCells('A' . $row . ':A' . $endRow)->getStyle('A'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('B' . $row . ':B' . $endRow)->getStyle('B'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('C' . $row . ':C' . $endRow)->getStyle('C'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('D' . $row . ':D' . $endRow)->getStyle('D'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('E' . $row . ':E' . $endRow)->getStyle('E'. $row)->getAlignment()->setVertical('center');
				//$sheet->mergeCells('AJ' . $row . ':AJ' . $endRow)->getStyle('AJ'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('F' . $row . ':F' . $endRow)->getStyle('F'. $row)->getAlignment()->setVertical('center');
				//$sheet->mergeCells('G' . $row . ':G' . $endRow)->getStyle('G'. $row)->getAlignment()->setVertical('center');
				//$sheet->mergeCells('H' . $row . ':H' . $endRow)->getStyle('H'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('I' . $row . ':I' . $endRow)->getStyle('I'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('J' . $row . ':J' . $endRow)->getStyle('J'. $row)->getAlignment()->setVertical('center');
				// '采购物料总金额','采购员', '裁剪日期','床号','裁剪员','订单数',

			}
			$bgcolor = 'FFFFFFFF';

			// '下单日期','订单号','SKU','工厂','订单类型'

			if($v['create_time'] > 0){
					$phpExcel->getActiveSheet()->setCellValue('B' . $row, $objDate::PHPToExcel($v['create_time']));
					$phpExcel->getActiveSheet()->getStyle('B' . $row)->getNumberFormat()->setFormatCode($objFormat::FORMAT_DATE_XLSX22);
			}else{
				$sheet->setCellValueExplicit('B' . $row,$v['create_time'],'s');
			}
			if($v['caichuang_over_time'] > 0){
					$phpExcel->getActiveSheet()->setCellValue('C' . $row, $objDate::PHPToExcel($v['caichuang_over_time']));
					$phpExcel->getActiveSheet()->getStyle('C' . $row)->getNumberFormat()->setFormatCode($objFormat::FORMAT_DATE_XLSX22);
			}else{
				$sheet->setCellValueExplicit('C' . $row,'','s');
			}
            $sheet->setCellValueExplicit('D' . $row,$v['caichuang_user_name'],'s');
			$sheet->setCellValueExplicit('E' . $row, $v['quantity'], 's');//订单数量
			$sheet->setCellValueExplicit('AM' . $row, $v['caigou_pricing'], 's');	// 核价
			$sheet->setCellValueExplicit('F' . $row, $v['o_type'], 's');	// 订单类型


			$sheet->setCellValueExplicit('I' . $row, $v['client_ordernum'], 's');//订单号
			$sheet->setCellValueExplicit('J' . $row, $v['sku'], 's');

			foreach ($v['omList'] as $sk => $sv) {
				/*  '材料名称','材料类别','开单采购数量','实际采购数量','缩水后数量','单位','采购物料单价','客户物料单价','客户单件用量','实际单件用量','客户单件物料成本','实际单件物料成本','采购物料单项金额','客户物料单项金额', '盈亏情况', */

				$sheet->setCellValueExplicit('G' . $row, $sv['mInfo']['supplier'], 's');//供应商
				$sheet->setCellValueExplicit('A' . $row, arrayGet(config('mimo.order_from'), $v['is_auto_import']), 's');	// 账号
				$sheet->setCellValueExplicit('H' . $row, $v['factory_name'], 's');

				//$sv['customer_price'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'customer_price', 0);
				$sv['weight'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'weight', 0);
				$sv['name'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'name', 0);
				$sv['purchasing_unit'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'purchasing_unit', 0);
				$sv['type'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'type', 0);
                if($export_material_type=='accessories'){ //导出辅料
                    if($sv['type']!="accessories") continue;
                }elseif($export_material_type=="all"){

                }else{
                    if($sv['type']=="accessories") continue;
                }
				$sheet->setCellValueExplicit('K' . $row, $sv['name'], 's');
				if ($sv['billing_caigou_count'] > $sv['shiji_caigou_count']) {
					$sheet->getStyle('L' . $row)->getFill()->applyFromArray($bgArr);
				}
				$sheet->setCellValueExplicit('L' . $row, $sv['billing_caigou_count'], 'n');
				$sheet->setCellValueExplicit('M' . $row, $sv['billing_caigou_count_feed'], 's');
                $metre=round(($sv['fabric_width_once']==0 || $sv['weight_once']==0)?0:10000/$sv['fabric_width_once']/$sv['weight_once'],2);
                $sheet->setCellValueExplicit('N' . $row, $sv['fabric_width_once']."/".$sv['weight_once']."/".$metre, 's');
                $metre=round(($sv['mInfo']['fabric_width']==0 || $sv['mInfo']['weight']==0)?0:10000/$sv['mInfo']['fabric_width']/$sv['mInfo']['weight'],2);
				$sheet->setCellValueExplicit('O' . $row, $sv['mInfo']['fabric_width']."/".$sv['mInfo']['weight']."/".$metre, 's');
				$metre_shiji=round(($sv['true_fabric_width']==0 || $sv['true_weight']==0)?0:10000/$sv['true_fabric_width']/$sv['true_weight'],2);
				$sheet->setCellValueExplicit('P' . $row, $sv['true_fabric_width']."/".$sv['true_weight']."/".$metre_shiji, 's');
				$sheet->setCellValueExplicit('Q' . $row, $sv['caichuang_fabric_width'], 'n');	// 实裁布封
				$sheet->setCellValueExplicit('R' . $row, $sv['billing_caigou_kgcount'], 'n');	// 开单采购公斤数
				$sheet->setCellValueExplicit('S' . $row, $sv['billing_caigou_kgprice'], 'n');	// 开单采购公斤价
				$sheet->setCellValueExplicit('T' . $row, $sv['shiji_weight'], 'n');	// 实际公斤数
				$sheet->setCellValueExplicit('U' . $row, $sv['tiaoshu'], 'n');	// 采购条数
				$sheet->setCellValueExplicit('V' . $row, $sv['checkcloth_length'], 'n');	// 验布米长
				$sheet->setCellValueExplicit('W' . $row, $sv['shrink_length'], 'n');	// 缩水米长
				$sheet->setCellValueExplicit('X' . $row, $sv['labu_lenght'], 'n');
				$sheet->setCellValueExplicit('Y' . $row, $sv['return_num'], 'n');
				$sheet->setCellValueExplicit('Z' . $row, $sv['return_length'], 'n');
				$sheet->setCellValueExplicit('AA' . $row, $sv['mInfo']['unit'], 's');

				$sheet->setCellValueExplicit('AB' . $row, $sv['loss'], 'n');
				if ($sv['caigou_unitprice'] > $sv['customer_price']) {
					$sheet->getStyle('AB' . $row)->getFill()->applyFromArray($bgArr);
					$sheet->getStyle('AC' . $row)->getFill()->applyFromArray($bgArr);
				}
				$sheet->setCellValueExplicit('AC' . $row, $sv['caigou_unitprice'], 'n');	// 采购物料单价
				$sheet->setCellValueExplicit('AD' . $row, $sv['customer_price'], 'n');		// 客户物料单价
				$shiji_dosage = ($sv['shicai_count'] ? round($sv['billing_caigou_count']/$sv['shicai_count']) : 0);
				if ($shiji_dosage > $sv['customer_dosage']) {
					$sheet->getStyle('AD' . $row)->getFill()->applyFromArray($bgArr);
					$sheet->getStyle('AE' . $row)->getFill()->applyFromArray($bgArr);
				}
				$sheet->setCellValueExplicit('AE' . $row, round($sv['caichuang_shiji_dosage'],2), 'n');//实际单件用量
				$sheet->setCellValueExplicit('AF' . $row, $sv['customer_dosage'], 'n');//客户单件用量

				$sv['shiji_caigou_subtotal_money']=$sv['shicai_count']==0?0:round($sv['caigou_subtotal_money']/$sv['shicai_count'],2);
				$sheet->setCellValueExplicit('AG' . $row, $sv['shiji_caigou_subtotal_money'], 'n');	// 实际单件物料成本
				$sheet->setCellValueExplicit('AH' . $row, $sv['custom_simple_cost'], 'n');		// 客户单件物料成本
				$sheet->setCellValueExplicit('AI' . $row, $sv['caigou_subtotal_money'], 'n'); //采购物料单项金额
                $sheet->setCellValueExplicit('AJ' . $row, $sv['col1'], 'n');//客户物料单项金额
                $sheet->setCellValueExplicit('AK' . $row, $sv['col1_2'], 'n');//客户物料单项金额-计算
                $sv['loss_pre']=round(($sv['customer_dosage'] * $sv['customer_price'] * (1+$sv['loss']/100) * $sv['shicai_count'])-$sv['caigou_subtotal_money']+($sv['fabric_price_amount']+$sv['dosage_price_amount']),2);
				$sheet->setCellValueExplicit('AL' . $row, $sv['win_money'], 'n');//盈亏情况
//                $sheet->setCellValueExplicit('AM' . $row, '', 'n');//核价  在上面的程序设置了。
                $sheet->setCellValueExplicit('AN' . $row, $sv['fabric_price_amount'], 'n');//面料核价金额
				$sheet->setCellValueExplicit('AO' . $row, $sv['dosage_price_amount'], 'n');//用量核价金额
				$sheet->setCellValueExplicit('AP' . $row, $sv['yingcai_count'], 'n');//预裁数
				$sheet->setCellValueExplicit('AQ' . $row, $sv['shicai_count'], 'n');//实裁数
				$sheet->setCellValueExplicit('AR' . $row, $sv['metre']*$sv['caigou_unitprice'], 'n');//余料金额
				$sheet->setCellValueExplicit('AS' . $row, $sv['metre'], 'n');//余料情况
				$sheet->setCellValueExplicit('AT' . $row, '', 'n');//补损金额
				$sheet->setCellValueExplicit('AU' . $row, '', 'n');//补损明细

				$sheet->setCellValueExplicit('AV' . $row, $sv['metre_dif'], 'n');
                $sheet->setCellValueExplicit('AW' . $row, $sv['metre_dif_count'], 'n');
                $sheet->setCellValueExplicit('AX' . $row, $sv['metre_dif_pre'], 'n');
                $sheet->setCellValueExplicit('AY' . $row, $sv['billing_caigou_kgcount_dif'], 'n');
                $sheet->setCellValueExplicit('AZ' . $row, $sv['billing_caigou_kgcount_dif_count'], 'n');
                $sheet->setCellValueExplicit('BA' . $row, $sv['caigou_unitprice_dif'], 'n');
                $sheet->setCellValueExplicit('BB' . $row, $sv['caigou_unitprice_dif_count'], 'n');
                $sheet->setCellValueExplicit('BC' . $row, $sv['weight_dif'], 'n');
                $sheet->setCellValueExplicit('BD' . $row, $sv['width_dif'], 'n');
                $sheet->setCellValueExplicit('BE' . $row, $sv['bsp_dif'], 'n');
                $sheet->setCellValueExplicit('BF' . $row, $sv['bsp_dif_count'], 'n');
                $sheet->setCellValueExplicit('BG' . $row, $sv['labu_lenght_dif'], 'n');
                $sheet->setCellValueExplicit('BH' . $row, $sv['labu_lenght_dif_count'], 'n');
                $sheet->setCellValueExplicit('BI' . $row, $sv['caichuang_dif'], 'n');
                $sheet->setCellValueExplicit('BJ' . $row, $sv['caichuang_dif_count'], 'n');
                $sheet->setCellValueExplicit('BK' . $row, $sv['material_per'], 'n');
                $sheet->setCellValueExplicit('BL' . $row, $sv['costing_remark'], 's');

//				$shiji_dosage = ($sv['shicai_count'] ? round($sv['billing_caigou_count']/$sv['shicai_count']) : 0);
//				if ($shiji_dosage > $sv['customer_dosage']) {
//					$sheet->getStyle('J' . $row)->getFill()->applyFromArray($bgArr);
//					$sheet->getStyle('K' . $row)->getFill()->applyFromArray($bgArr);
//				}
//				$sheet->setCellValueExplicit('J' . $row, $sv['customer_dosage'], 'n');		// 客户单件用量
//				$sheet->setCellValueExplicit('K' . $row, $sv['caichuang_shiji_dosage'], 'n');			// 实际单件用量
//
//				$sheet->setCellValueExplicit('L' . $row, $sv['custom_simple_cost'], 'n');	// 客户单件物料成本
//				$sheet->setCellValueExplicit('M' . $row, ($sv['shicai_count'] ? round($sv['caigou_subtotal_money']/$sv['shicai_count']) : 0), 'n');	// 实际单件物料成本
//				$sheet->setCellValueExplicit('N' . $row, $sv['caigou_subtotal_money'], 'n'); // 采购物料单项金额
//				$khwldxje = round($sv['customer_dosage'] * $sv['customer_price'] * (1+$sv['loss']/100) * $sv['shicai_count'], 2);
//				$sheet->setCellValueExplicit('O' . $row, $khwldxje, 'n'); // 客户物料单项金额
//
//				$yk = round($sv['customer_dosage'] * $sv['customer_price'] * (1+$sv['loss']/100) * $sv['shicai_count'] - $sv['caigou_subtotal_money'], 2);
//				$sheet->setCellValueExplicit('P' . $row, $yk, 'n');	//盈亏情况
				// '客户克重', '实际克重', '预裁数', '实裁数', '捆条 ', '配布 ', '布头'
//				$sv['caichuang_strip'] = floatval($sv['caichuang_strip']);
//				$sv['caichuang_neadend'] = floatval($sv['caichuang_neadend']);
//				$sv['caichuang_adaption'] = floatval($sv['caichuang_adaption']);
//				$ycs = $sv['customer_dosage']>0 ? round(($sv['shrink_length']-$sv['caichuang_strip']-$sv['caichuang_neadend']-$sv['caichuang_adaption'])/($sv['customer_dosage'] * (1+$sv['loss']/100)), 2) : 0;
				$row++;
			}
			unset($v);
			unset($data[$k]);
		}

		// Rename worksheet
		$sheet->setTitle('worksheet');

		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1');
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
		header ('Cache-Control: cache, must-revalidate');
		header ('Pragma: public');

		$objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
		$objWriter->save('php://output');
		exit();
	}

	/**
	 * 物料成本核算审核
	 *
	 * @author King
	 * @date 2020年8月5日
	 *
	 */
	public function audit() {
		$orderId       = $this->request->param('order_id/d', 0);
        $orderIds       = $this->request->param('id');

		if($orderId>0){
		    $res=$this->audit_real_one($orderId);
            return $this->Json($res['code'],$res['msg']);
        }
		if(count($orderIds)>0){
		    foreach ($orderIds as $k=>$v){
                $res=$this->audit_real_one(intval($v));
                if($res['code']==0){
                    return $this->Json($res['code'],$res['msg']);
                }
            }
            return $this->Json($res['code'],$res['msg']);
        }
	}

    public function audit_real_one($orderId)
    {
        $orderInfo = (new OrderService())->getInfoById($orderId);
        if (empty($orderInfo)) {
            return ['code' => 0, 'msg' => '订单不存在',];
        }
        if ($orderInfo['cost_audit_status'] == 1) {
            return ['code' => 0, 'msg' => '此订单已审核',];
        }
        try {
            db()->startTrans();
            $time = time();
            $upData = [
                'cost_audit_status' => 1,
                'cost_audit_time' => $time,
                'update_time' => $time,
            ];
            db('order')->where('id', $orderId)->update($upData);
            db()->commit();
            return ['code' => 1, 'msg' => '成功'];
        } catch (\Exception $e) {
            db()->rollback();
            return ['code' => 0, 'msg' => '操作失败',];
        }
    }
	/**
	 * 查看合裁订单气泡
	 *
	 * @author 飞燕
	 * @date 2021年5月14日
	 *
	 */
	public function omcOrdernum(){
		$clientOrdernum   = $this->request->param('client_ordernum/s', '');
		if ($this->request->isAjax()) {
			$orderMergeCutService=new OrderMergeCutService();
			$clientOrdernumArr=$orderMergeCutService->getInfoByClientOrdernum($clientOrdernum, 'client_ordernum');
			$data['data']="";
			$data['code']=0;
			if($clientOrdernumArr) {
				$data['code']=1;
				$data['data']=$clientOrdernumArr['client_ordernum'];
			};
			return json($data);
		}

	}
}